package com.goldplusgold.tradedelay.app.trade.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.goldplusgold.support.lib.base.fragment.BaseFragment;
import com.goldplusgold.support.lib.widget.AsyncTask;
import com.goldplusgold.support.lib.widget.horizontallistview.SyncHorizontalScrollView;
import com.goldplusgold.support.lib.widget.pulltorefresh.PullToRefreshBase;
import com.goldplusgold.support.lib.widget.pulltorefresh.PullToRefreshListView;
import com.goldplusgold.tradedelay.app.R;
import com.goldplusgold.tradedelay.app.trade.adapter.AdapterEntrust;
import com.goldplusgold.tradedelay.app.trade.networkservice.TradeService;
import com.goldplusgold.tradedelay.app.trade.pojo.EntrustList;
import com.goldplusgold.tradedelay.app.trade.pojo.EntrustOrder;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;

/**
 * Created by admin on 2017/5/15.
 */

public class EntrustFragment extends BaseFragment implements Handler.Callback, PullToRefreshListView.OnRefreshListener2 {
    @BindView(R.id.id_head_list_view_entrust)
    LinearLayout mHeadListViewPosition;
    @BindView(R.id.head_content_horsv)
    SyncHorizontalScrollView mheadContentHorsv;
    @BindView(R.id.id_bottom_list_view_entrust)
    PullToRefreshListView mBottomListViewPosition;
    private AdapterEntrust mAdapterEntrust;
    private int mPageIndex = 1;
    private int mPageSize = 10;

    private final static int NETWORK_ERROR_CODE = 0x01;
    private Handler handler = new Handler(this);
   /* private Timer timer;
    private AlarmTask alarmTask;*/

    public static EntrustFragment newInstance() {

        Bundle args = new Bundle();

        EntrustFragment fragment = new EntrustFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_entrust;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
      /*  timer = new Timer();
        alarmTask = new AlarmTask();*/
    }

  /*  public class AlarmTask extends TimerTask {
        @Override
        public void run() {
            //任务代码写在此处
            new LoadEntrustListAsyncTask().execute(AsyncTask.TYPE_NET);
            Log.d("refreshTest", "委托数据刷新了");
        }
    }*/

    @Override
    protected void initView() {
        super.initView();
        mBottomListViewPosition.setFocusable(false);
        List<String> titles = Arrays.asList(
                "状态", "类型",
                "委托价",
                "手数",
                "可撤",
                "委托时间"
        );
        for (String str : titles) {
            View childView = LayoutInflater.from(getContext()).inflate(R.layout.item_horizontal_position, mHeadListViewPosition, false);
            TextView mTextViewHorizontal = (TextView) childView.findViewById(R.id.id_text_view_horizontal);
            mTextViewHorizontal.setTextSize(TypedValue.COMPLEX_UNIT_SP, 11);
            mTextViewHorizontal.setText(str);
            mHeadListViewPosition.addView(childView);
        }
        getChildFragmentManager();
        mAdapterEntrust = new AdapterEntrust(getActivity());
        mAdapterEntrust.setFragmentRef(getParentFragment());
        mAdapterEntrust.addHead(mheadContentHorsv);
        mheadContentHorsv.setOnScrollListenter(mAdapterEntrust);
        mBottomListViewPosition.setOnItemClickListener(mAdapterEntrust);
        mBottomListViewPosition.setAdapter(mAdapterEntrust);
        mBottomListViewPosition.setOnRefreshListener(this);
        mBottomListViewPosition.setMode(PullToRefreshBase.Mode.BOTH);
        //timer.schedule(alarmTask, 0, 5*1000);
        new LoadEntrustListAsyncTask().execute(AsyncTask.TYPE_NET);
    }


    @Override
    public boolean handleMessage(Message msg) {
        int type = msg.what;
        switch (type) {
            case NETWORK_ERROR_CODE:
                showToastMessage(R.string.network_error, Toast.LENGTH_LONG);
                break;
        }

        return true;
    }


    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        mPageIndex = 1;
        new LoadEntrustListAsyncTask().execute(AsyncTask.TYPE_NET);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        mPageIndex++;
        new LoadEntrustListAsyncTask().execute(AsyncTask.TYPE_NET);
    }


    public class LoadEntrustListAsyncTask extends AsyncTask<Void, Void, List<EntrustOrder>> {


        @Override
        protected List<EntrustOrder> doInBackground(Void... params) {

            try {
                EntrustList entrustList = TradeService.getInstance().getEntrustList(String.valueOf(mPageIndex), String.valueOf(mPageSize));
                if (entrustList != null) {
                    return entrustList.getEntrustOrders();
                }
            } catch (Exception e) {
                e.printStackTrace();
                sendNetworkErrorMessage();
            }

            return null;
        }

        @Override
        protected void onPostExecute(List<EntrustOrder> entrustList) {
            super.onPostExecute(entrustList);
            if (!isAvailableActivity()) {
                return;
            }
            mBottomListViewPosition.onRefreshComplete();
            if (entrustList == null || entrustList.isEmpty()) {
                return;
            }

            if (mPageIndex > 1) {
                mAdapterEntrust.addArrayList(new ArrayList(entrustList));
            } else {
                mAdapterEntrust.setArrayList(new ArrayList(entrustList));
            }
        }
    }


    private void sendNetworkErrorMessage() {
        Message message = handler.obtainMessage();
        message.what = NETWORK_ERROR_CODE;
        handler.sendMessage(message);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //alarmTask.cancelAll();
    }
}
